<template>
  <div class="app-container">
    <el-dialog :title="popTitle" :visible.sync="visible" :width="popTitle === '热点管理' ? '1200px' : '800px'"
      :before-close="handleClose" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="12">
            <el-form-item label="全景图名称" prop="title">
              <el-input v-model="form.title" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示楼层名称" prop="floorTitle">
              <el-input v-model="form.floorTitle" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId">
              <el-select v-model="form.floorId" placeholder="请选择楼层" clearable size="small">
                <el-option v-for="dict in floorArr" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="12">
            <el-form-item label="初始俯仰角" prop="initialPitch">
              <el-input v-model="form.initialPitch" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初始偏航角" prop="initialYaw">
              <el-input v-model="form.initialYaw" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="12">
            <el-form-item label="初始水平角" prop="initialHfov">
              <el-input v-model="form.initialHfov" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="24">
            <el-form-item label="全景图" prop="panoramaPathurl">
              <FileUpload ref="fileUpload" v-model="form.panoramaPathurl" :file-type="['png', 'jpg', 'jpeg']" :url="url"
                :dynamic-headers="dynamicHeaders" :dynamic-method="dynamicMethod" :dynamic-url="dynamicUrl"
                :oss-id="ossId" @input="getFirelist" :limit="1" @deleteFile="deleteFile" :drag="true"
                :list-type="'picture'" :who="'panoramaPathurl'" @giveMediaType="giveMediaType" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="popTitle !== '热点管理'">
          <el-col :span="24">
            <el-form-item label="预览图" prop="previewPathurl">
              <FileUpload ref="fileUpload2" v-model="form.previewPathurl" :file-type="['png', 'jpg', 'jpeg']" :url="url"
                :dynamic-headers="dynamicHeaders" :dynamic-method="dynamicMethod" :dynamic-url="dynamicUrl"
                :oss-id="ossId" @input="getFirelist" :limit="1" @deleteFile="deleteFile" :drag="true"
                :list-type="'picture'" :who="'previewPathurl'" @giveMediaType="giveMediaType" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row v-show="popTitle === '热点管理'">
        <el-col :span="24">
          <!-- <el-form-item label="热点" prop=""> -->
          <pannellumCon v-if="form.panoramaPathurl" ref="pannellumCon" />
          <div v-show="!form.panoramaPathurl">
            <span class="empty">选择全景图后显示</span>
          </div>
          <!-- </el-form-item> -->
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import editorCom from '@/components/Editor'
import { postOssUpload } from '@/api/oss'
import { addvrPanorama, editvrPanorama, getPanorama } from '@/api/pannellum'
import { getfloorArr } from '@/api/map'
import pannellumCon from './pannellum.vue'
import { signedDecimalRules, specialRules } from '@/utils/rules'
export default {
  name: 'Add',
  components: {
    FileUpload,
    editorCom,
    pannellumCon
  },
  props: {
    id: {
      type: [Number, String],
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    objTarget: {
      type: String,
      default: ''
    },
    popTitle: {
      type: String,
      default: ''
    }
  },
  data() {
    // 定义校验规则
    const validatetitle = (rule, value, callback) => {
      if (!value) {
        callback(new Error('全景图名称不能为空'))
      } else if (!specialRules.test(value)) {
        callback(new Error('请输入合法的全景图名称'))
      } else {
        callback()
      }
    }
    const validatefloorTitle = (rule, value, callback) => {
      if (!value) {
        callback(new Error('展示楼层名称不能为空'))
      } else if (!specialRules.test(value)) {
        callback(new Error('请输入合法的展示楼层名称'))
      } else {
        callback()
      }
    }
    const validateinitialPitch = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback(new Error('初始俯仰角不能为空'))
      } else if (!signedDecimalRules.test(value)) {
        callback(new Error('初始俯仰角只能为正负数或零，小数点后最多两位'))
      } else {
        callback()
      }
    }
    const validateinitialYaw = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback(new Error('初始偏航角不能为空'))
      } else if (!signedDecimalRules.test(value)) {
        callback(new Error('初始偏航角只能为正负数或零，小数点后最多两位'))
      } else {
        callback()
      }
    }
    const validateinitialHfov = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback(new Error('初始水平角不能为空'))
      } else if (!signedDecimalRules.test(value)) {
        callback(new Error('初始水平角只能为正负数或零，小数点后最多两位'))
      } else {
        callback()
      }
    }
    return {
      form: {},
      uploadParams: {
        path: 'map-building',
        name: '',
        permission: 'tenant',
        suffix: '',
        mediaType: '',
        sizeLimit: '',
        attachment: ''
      },
      rules: {
        title: [{ required: true, validator: validatetitle, trigger: 'blur' }],
        floorTitle: [
          { required: true, validator: validatefloorTitle, trigger: 'blur' }
        ],
        floorId: [{ required: true, message: '请选择楼层', trigger: 'change' }],
        initialPitch: [
          { required: true, validator: validateinitialPitch, trigger: 'blur' }
        ],
        initialYaw: [
          { required: true, validator: validateinitialYaw, trigger: 'blur' }
        ],
        initialHfov: [
          { required: true, validator: validateinitialHfov, trigger: 'blur' }
        ],
        panoramaPathurl: [
          { required: true, message: '请上传全景图', trigger: 'change' }
        ],
        previewPathurl: [
          { required: true, message: '请上传预览图', trigger: 'change' }
        ]
      },
      url: '',
      ossId: '',
      dynamicHeaders: {},
      dynamicMethod: 'PUT',
      dynamicUrl: null,
      panoramaOidList: [], // 全景图
      previewOidList: [], // 全景预览图
      baseurl: null,
      floorArr: [],
      sceneArr: []
    }
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail()
        }
      },
      deep: false,
      immediate: true
    },
    visible: {
      handler(val) {
        if (val) {
          this.requestfloorArr(0)
          this.requestgetPanorama()
        }
      },
      deep: false,
      immediate: true
    }
  },
  methods: {
    requestgetPanorama() {
      getPanorama()
        .then((res) => {
          const arr = res?.data ?? []
          this.sceneArr = []
          if (arr.length > 0) {
            arr.map((item) => {
              const obj = {
                label: item.title,
                value: item.sceneId + ''
              }
              this.sceneArr.push(obj)
            })
          }
          this.$refs.pannellumCon.giveSceneArr(this.sceneArr)
        })
        .catch((error) => { })
    },
    // 初始化全景图场景
    initScene(hotspots) {
      setTimeout(() => {
        this.$refs.pannellumCon.initPannellum(this.baseurl, hotspots, this.form)
      }, 100)
    },
    requestfloorArr(id) {
      this.floorArr = []
      getfloorArr(id)
        .then((res) => {
          if (res.success) {
            const arr = res?.data ?? []
            if (arr.length > 0) {
              arr.map((item) => {
                const obj = {
                  label: item.mapName,
                  value: item.mapId
                }
                this.floorArr.push(obj)
              })
            }
          }
        })
        .catch((err) => { })
    },
    handleInput(val) {
      this.form.description = val
    },
    giveDetail() {
      const objTarget = JSON.parse(this.objTarget)
      this.form = {
        title: objTarget.title,
        floorTitle: objTarget.floorTitle,
        floorId: objTarget.floorId,
        initialPitch: objTarget.initialPitch,
        initialYaw: objTarget.initialYaw,
        initialHfov: objTarget.initialHfov,
        panoramaPathurl: [objTarget.panoramaPathurl],
        previewPathurl: [objTarget.previewPathurl],
        sceneNo: objTarget.sceneNo
      }
      this.baseurl = objTarget.panoramaPathurl
      this.panoramaOidList = [objTarget.panoramaPathoid]
      this.previewOidList = [objTarget.previewPathoid]
      const hotspots = objTarget.hotspots
      this.initScene(hotspots)
    },
    giveMediaType(mediaType, who) {
      this.uploadParams.mediaType = mediaType
      this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1]
      this.requestpostOssUpload(who)
    },
    requestpostOssUpload(who) {
      if (who === 'panoramaPathurl') {
        this.uploadParams.name = '全景图'
        this.uploadParams.path = 'vr-panoramaPathurl'
      } else {
        this.uploadParams.name = '预览图'
        this.uploadParams.path = 'vr-previewPathurl'
      }
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {}
            this.dynamicMethod = res.data.method || 'PUT'
            this.dynamicUrl = res.data.uploadUrl || ''
            this.ossId = res?.data?.ossId ?? null
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getFirelist(data, who) {
      let arr
      data.forEach((item) => {
        if (who === 'panoramaPathurl') {
          arr = this.panoramaOidList
        } else if (who === 'previewPathurl') {
          arr = this.previewOidList
        }
        if (item.ossId && !arr.includes(item.ossId)) {
          arr.push(item.ossId)
          if (who === 'panoramaPathurl') {
            this.baseurl = item.url
            this.initScene()
          }
        }
      })
      setTimeout(() => {
        this.$refs.pannellumCon.giveSceneArr(this.sceneArr)
      }, 100)
      this.dynamicHeaders = {}
      this.dynamicMethod = 'PUT'
      this.dynamicUrl = null
      this.ossId = ''
      console.log(this.form, arr)
    },
    deleteFile(file, who) {
      let flage, arr
      if (who === 'panoramaPathurl') {
        flage = this.form.panoramaPathurl
        arr = this.panoramaOidList
      } else if (who === 'previewPathurl') {
        flage = this.form.previewPathurl
        arr = this.previewOidList
      }
      // 找到form.file中对应的对象，删除
      const index = flage.findIndex((item) => {
        if (typeof item === 'object' && Object.keys(item).length > 0) {
          return item.url === file.url
        } else {
          return item === file.url
        }
      })
      if (index !== -1) {
        // 找到panoramaOidList中对应的对象，删除
        flage.splice(index, 1)
        arr.splice(index, 1)
      }
    },
    cancle() {
      this.handleClose(false)
    },
    async sub() {
      // 触发表单校验
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const hotspotsInfoData =
            await this.$refs.pannellumCon.delHotspotData()
          if (hotspotsInfoData === false) {
            return
          }
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg
          const queryParams = {
            title: this.form.title,
            floorTitle: this.form.floorTitle,
            floorId: this.form.floorId,
            initialPitch: Number(this.form.initialPitch),
            initialYaw: Number(this.form.initialYaw),
            initialHfov: Number(this.form.initialHfov),
            panoramaPathoid: this.panoramaOidList[0],
            previewPathoid: this.previewOidList[0],
            hotspots: hotspotsInfoData,
            sceneNo: this.form.sceneNo ?? Date.now() / 1000
          }
          if (this.id) {
            requestWay = editvrPanorama
            queryParams.sceneId = this.id
            msg = '修改成功'
            errmsg = '修改失败'
          } else {
            requestWay = addvrPanorama
            msg = '新增成功'
            errmsg = '新增失败'
          }
          console.log('提交表单数据:', queryParams)
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg)
                this.handleClose(true)
              } else {
                this.$message.error(errmsg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    handleClose(status) {
      this.form = {}
      this.panoramaOidList = []
      // 重置表单
      this.$refs.form.resetFields()
      // this.$refs.pannellumCon.resetHotspots();
      this.$emit('update:visible', false)
      this.$emit('close', status === true ? status : false)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/index.scss";

.empty {
  font-size: 20px;
  color: $themeColor;
}
</style>
